package com.ccteam.shared.domain.auth

import com.ccteam.model.Resource
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.auth.AuthRepository
import com.ccteam.shared.domain.SuspendUseCase
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/5
 *
 * 用户退出登录Domain层
 * 传入[Nothing]
 * 返回[Nothing]
 */
class LogoutDataUseCase @Inject constructor(
    private val userCore: UserCore,
    private val authRepository: AuthRepository
): SuspendUseCase<Nothing?, Nothing?>(
    Dispatchers.IO
) {
    override suspend fun execute(parameters: Nothing?): Resource<Nothing?> {
        val isLogin = userCore.isLogin.value
        val userInfo = userCore.userInfo.value
        if(!isLogin || userInfo.userToken.isNullOrEmpty()){
            userCore.logout()
            return Resource.Success(null)
        }
        return when(val result = authRepository.logoutUser(userInfo.userToken)){
            is ApiResult.Success ->{
                userCore.logout()
                Resource.Success(null)
            }
            is ApiResult.Failure ->{
                Resource.Error(result.errorCode,result.errorMsg)
            }
            is ApiResult.Empty ->{
                Resource.Error(ApiError.unknownCode,"未知错误")
            }
        }
    }
}